
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <pthread.h>

#define SERVER_IP "192.168.75.67"
#define PORT 8080
#define BUFFER_SIZE 1024

void* send_handler(void* arg) {
    int sockfd = (int)(intptr_t)arg;
    char buffer[BUFFER_SIZE];

    while (1) {
        fgets(buffer, BUFFER_SIZE, stdin);
        buffer[strcspn(buffer, "\n")] = '\0'; // 移除换行符
        
        if (send(sockfd, buffer, strlen(buffer), 0) < 0) {
            perror("send failed");
            break;
        }
        
        if (strcmp(buffer, "exit") == 0) {
            shutdown(sockfd, SHUT_WR); // 半关闭连接
            break;
        }
    }
    return NULL;
}

void* recv_handler(void* arg) {
    int sockfd = (int)(intptr_t)arg;
    char buffer[BUFFER_SIZE];
    ssize_t bytes_received;

    while ((bytes_received = recv(sockfd, buffer, BUFFER_SIZE-1, 0)) > 0) {
        buffer[bytes_received] = '\0';
        printf("Server response: %s\n", buffer);
    }

    if (bytes_received < 0) {
        perror("recv error");
    } else {
        printf("Connection closed by server\n");
    }
    
    return NULL;
}

int main() {
    int sockfd;
    struct sockaddr_in server_addr;
    pthread_t send_thread, recv_thread;

    // 创建socket
    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        perror("socket creation failed");
        exit(EXIT_FAILURE);
    }

    // 配置服务器地址
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(PORT);
    
    if (inet_pton(AF_INET, SERVER_IP, &server_addr.sin_addr) <= 0) {
        perror("invalid address");
        close(sockfd);
        exit(EXIT_FAILURE);
    }

    // 连接服务器
    if (connect(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)) )
    {
        perror("connection failed");
        close(sockfd);
        exit(EXIT_FAILURE);
    }

    printf("Connected to server at %s:%d\n", SERVER_IP, PORT);
    printf("Enter messages ('exit' to quit):\n");

    // 创建收发线程
    if (pthread_create(&send_thread, NULL, send_handler, (void*)(intptr_t)sockfd)) {
        perror("send thread creation failed");
        close(sockfd);
        exit(EXIT_FAILURE);
    }

    if (pthread_create(&recv_thread, NULL, recv_handler, (void*)(intptr_t)sockfd)) {
        perror("recv thread creation failed");
        close(sockfd);
        exit(EXIT_FAILURE);
    }

    // 等待线程结束
    pthread_join(send_thread, NULL);
    pthread_join(recv_thread, NULL);

    close(sockfd);
    return 0;
}